#include "csphere.h"
#include <QDebug>

CSphere::CSphere(CPoint3f position, float r, CMaterial mat)
{
	this->position = position;
	this->Rayon = r;
	this->material = mat;
}

void CSphere::paint()
{
	glPushMatrix();
		glTranslatef(this->position.GetX(), this->position.GetY(), this->position.GetZ());
		GLUquadric *quadric;
		quadric = gluNewQuadric();
		gluQuadricDrawStyle(quadric, GLU_FILL);
		gluQuadricNormals(quadric, GLU_SMOOTH);
		/* If we ever changed/used the texture or orientation state
		of quadObj, we'd need to change it to the defaults here
		with gluQuadricTexture and/or gluQuadricOrientation. */
		gluSphere(quadric, this->Rayon, 32, 32);
	glPopMatrix();
}

bool CSphere::intersect(CRay * Ray, CPoint3f & P, CVecteur3f & V)
{
	// intersection rayon/sphere
	float t = 20000.0f;
	CVecteur3f dist(Ray->depart, this->position);
	float B = Ray->direction * dist;
	float D = B*B - (dist*dist) + this->Rayon * this->Rayon;
	if (D < 0.0f)
		return false;
	float t0 = B - sqrtf(D);
	float t1 = B + sqrtf(D);
	bool retvalue = false;
	if ((t0 > 0.1f) && (t0 < t))
	{
		t = t0;
		retvalue = true;
	}
	if ((t1 > 0.1f) && (t1 < t))
	{
		t = t1;
		retvalue = true;
	}
	if (retvalue)
	{
		P = (CPoint3f)(Ray->depart) + (CVecteur3f)(Ray->direction)*t;
                V = CVecteur3f(this->position,P);
                V.normalize();
		return true;
	}
	else return false;


}
